package cn.llming.org.service.impl;


import cn.llming.basic.service.impl.BaseServiceImpl;
import cn.llming.org.domain.Department;
import cn.llming.org.mapper.DepartmentMapper;

import cn.llming.org.service.IDepartmentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService{

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void insert(Department department) {
        //创建时间
        department.setCreateTime(new Date());
        String path="";
        if(Objects.nonNull(department.getParent()) && Objects.nonNull(department.getParent().getId())){
            //获取父部门的path
            Department byId = departmentMapper.getById(department.getParent().getId());
            System.out.println(byId);
            if(byId !=null && byId.getPath()!=null){
                path=byId.getPath();
            }
        }
        //更新path
        departmentMapper.insert(department);
        path=path+"/"+department.getId();

        department.setPath(path);
        departmentMapper.update(department);
    }
    @Override
    @Transactional
    public void update(Department department) {
        String path="";
        if(Objects.nonNull(department.getParent()) && Objects.nonNull(department.getParent().getId())){
            //获取父部门的path
            Department byId = departmentMapper.getById(department.getParent().getId());
            if(byId !=null && byId.getPath()!=null){
                path=byId.getPath();
            }
        }
        //修改时间
        path=path+"/"+department.getId();
        department.setPath(path);
        department.setUpdateTime(new Date());

        departmentMapper.update(department);

    }

    @Override
    public List<Department> getDeptTree() {

        return departmentMapper.getTree();
    }
}
